<template>
  <el-container class="data-content">
    <el-aside width="300px" v-loading="showDicloading">
      <el-container>
        <el-header>
          <el-input placeholder="输入关键字进行过滤" v-model="dicFilterText" clearable></el-input>
        </el-header>
        <el-main class="nopadding">
          <el-tree ref="dic" class="menu" node-key="id" :data="dicList" :props="dicProps" :highlight-current="true"
                   :expand-on-click-node="false" :filter-node-method="dicFilterNode" @node-click="dicClick">
            <template #default="{node, data}">
							<span class="custom-tree-node">
								<span class="label">{{ data.title }}</span>
								<span class="code">{{ data.dataKey }}</span>
								<span class="do">
									<el-button-group>
										<el-button :icon="Edit" size="small" @click.stop="dicEdit(data)"></el-button>
										<el-button :icon="Delete" size="small" @click.stop="dicDel(node, data)"></el-button>
									</el-button-group>
								</span>
							</span>
            </template>
          </el-tree>
        </el-main>
        <el-footer style="height:51px;">
          <el-button type="primary" size="small" icon="el-icon-plus" style="width: 100%;" @click="addDic">字典分类
          </el-button>
        </el-footer>
      </el-container>
    </el-aside>
    <el-container class="is-vertical">
      <el-header>
        <div class="left-panel">
          <el-button type="primary" :icon="Plus" @click="addInfo" :disabled="selectData.id ===undefined"></el-button>
          <el-button :icon="Delete" type="danger" @click="batch_del" :disabled="selection.length === 0">
            批量删除 <span v-if="selection.length > 0">({{ selection.length }})</span>
          </el-button>
        </div>
      </el-header>
      <el-main class="nopadding">
        <el-table ref="table" row-key="id" :data="tableData.data" @selection-change="selectionChange"
                  stripe :paginationLayout="'prev, pager, next'">
          <el-table-column type="selection" width="50"></el-table-column>
          <el-table-column label="排序号" prop="sortNum" width="150" sortable></el-table-column>
          <el-table-column label="名称" prop="dataCode" width="150"></el-table-column>
          <el-table-column label="键值" prop="dataValue"></el-table-column>
          <el-table-column label="操作" fixed="right" align="right" width="120">
            <template #default="scope">
              <el-button-group>
                <el-button text type="primary" size="small" @click="table_edit(scope.row, scope.$index)">编辑
                </el-button>
                <el-popconfirm title="确定删除吗？" @confirm="table_del(scope.row, scope.$index)">
                  <template #reference>
                    <el-button text type="danger" size="small">删除</el-button>
                  </template>
                </el-popconfirm>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
    </el-container>
  </el-container>

  <dic-dialog v-if="dialog.dic" ref="dicDialogId" @success="handleDicSuccess" @closed="dialog.dic=false"></dic-dialog>

  <list-dialog v-if="dialog.list" ref="listDialogId" @success="handleListSuccess"
               @closed="dialog.list=false"></list-dialog>


  <BatchDelete
      v-model:visible="batchDeleteDialogVisible"
      :selected-items="selection"
      delete-url="/dictItem/delete"
      id-field="id"
      @delete-success="handleBatchDeleteSuccess"
  />

</template>

<script setup>
import {nextTick, onMounted, reactive, ref, watch} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import dicDialog from './dic.vue'
import listDialog from './list.vue'
import Sortable from 'sortablejs'
import {Delete, Edit, Plus} from '@element-plus/icons-vue'
import http from "@/utils/request.js";
import BatchDelete from "@/components/BatchDelete.vue";

// 响应式数据
const dic = ref(null)
const table = ref(null)
const dicDialogId = ref(null)
const listDialogId = ref(null)
const batchDeleteDialogVisible = ref(false);


const dialog = reactive({
  dic: false,
  info: false
})

const showDicloading = ref(true)
const dicList = ref([])
const dicFilterText = ref('')
const dicProps = reactive({
  label: 'name'
})

const listApi = ref(null)
const selection = ref([])
const selectData = ref([])
const tableData = reactive({})

// 监听器
watch(dicFilterText, (val) => {
  dic.value.filter(val)
})

// 生命周期
onMounted(() => {
  getDic()
  // rowDrop()
})

// 方法
// 加载树数据
const getDic = async () => {
  let res = await http.post("/dict/list", {})
  showDicloading.value = false
  dicList.value = res.data
}

// 树过滤
const dicFilterNode = (value, data) => {
  if (!value) return true
  const targetText = data.title + data.dictKey
  return targetText.indexOf(value) !== -1
}

// 树增加
const addDic = () => {
  dialog.dic = true
  nextTick(() => {
    dicDialogId.value.open()
  })
}

// 编辑树
const dicEdit = (data) => {
  dialog.dic = true
  nextTick(() => {
    dicDialogId.value.open('update');
    dicDialogId.value.setData(data);
  })
}

// 树点击事件
const dicClick = async (data) => {
  selectData.value = data;
  let res = await http.post(`/dictItem/list`, {dict: data.id})
  if (res.code === 200) {
    Object.assign(tableData, res)
  }
}

// 删除树
const dicDel = (node, data) => {
  ElMessageBox.confirm(`确定删除 ${data.title} 项吗？`, '提示', {
    type: 'warning'
  }).then(async () => {
    showDicloading.value = true

    let res = await http.post(`/dict/delete`, data)
    if (res.code !== 200) {
      ElMessage.error(res.msg)
      return
    }
    showDicloading.value = false

    // 删除节点是否为高亮当前 是的话 设置第一个节点高亮
    var dicCurrentKey = dic.value.getCurrentKey()
    dic.value.remove(data.id)
    if (dicCurrentKey === data.id) {
      var firstNode = dicList.value[0]
      if (firstNode) {
        dic.value.setCurrentKey(firstNode.id)
        table.value.upData({
          code: firstNode.code
        })
      } else {
        listApi.value = null
        table.value.tableData = []
      }
    }

    ElMessage.success("操作成功")
  }).catch(() => {
    // 用户取消删除
  })
}

// 行拖拽
const rowDrop = () => {
  const tbody = table.value.$el.querySelector('.el-table__body-wrapper tbody')
  Sortable.create(tbody, {
    handle: ".move",
    animation: 300,
    ghostClass: "ghost",
    onEnd({newIndex, oldIndex}) {
      const tableData = table.value.tableData
      const currRow = tableData.splice(oldIndex, 1)[0]
      tableData.splice(newIndex, 0, currRow)
      ElMessage.success("排序成功")
    }
  })
}

// 添加明细
const addInfo = () => {
  dialog.list = true
  nextTick(() => {
    listDialogId.value.open(selectData.value.id)
  })
}

// 编辑明细
const table_edit = (row) => {
  dialog.list = true
  nextTick(() => {
    listDialogId.value.open(row.dict);
    listDialogId.value.setData(row);
  })
}

// 删除明细
const table_del = async (row, index) => {
  const reqData = {id: row.id}
  let res = await http.post(`/dictItem/delete`, reqData)
  if (res.code === 200) {
    loadItems()
    ElMessage.success("删除成功")
  } else {
    ElMessageBox.alert(res.msg, "提示", {type: 'error'})
  }
}
const handleBatchDeleteSuccess = (result) => {
  if (result.success > 0) {
    // 刷新列表
    loadItems();
    // 清空选中
    selection.value = [];
  }
};
const loadItems = async () => {
  let res = await http.post(`/dictItem/list`, {dict: selectData.value.id})
  Object.assign(tableData, res)
}

// 批量删除
const batch_del = async () => {
  batchDeleteDialogVisible.value = true
}


// 表格选择后回调事件
const selectionChange = (selectionData) => {
  selection.value = selectionData
}


// 本地更新数据
const handleDicSuccess = (data, mode) => {
  getDic()
}

// 本地更新数据
const handleListSuccess = (data, mode) => {
  loadItems()
}
</script>

<style scoped>
.menu:deep(.el-tree-node__label) {
  display: flex;
  flex: 1;
  height: 100%;
}

.custom-tree-node {
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 24px;
  height: 100%;
}

.custom-tree-node .code {
  font-size: 12px;
  color: #999;
}

.custom-tree-node .do {
  display: none;
}

.custom-tree-node:hover .code {
  display: none;
}

.custom-tree-node:hover .do {
  display: inline-block;
}
</style>
